package com.ytrsoft.base;

import javax.swing.*;
import javax.swing.text.*;

public class JNumberField extends JTextField {

    public JNumberField() {
        ((AbstractDocument) this.getDocument()).setDocumentFilter(new NumericDocumentFilter());
    }

    public int getNumberValue() {
        String text = getText();
        if (text.isEmpty()) {
            return 0;
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private class NumericDocumentFilter extends DocumentFilter {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if (isNumeric(string)) {
                super.insertString(fb, offset, string, attr);
            }
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            if (isNumeric(string)) {
                super.replace(fb, offset, length, string, attr);
            }
        }

        private boolean isNumeric(String str) {
            if (str == null || str.isEmpty()) {
                return false;
            }
            String currentText = JNumberField.this.getText();
            String potentialText = currentText.substring(0, getSelectionStart()) + str + currentText.substring(getSelectionEnd());
            try {
                int value = Integer.parseInt(potentialText);
                return value >= 0;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }

}
